//
//  NSString+Extension.m
//  MiGuPlay
//
//  Created by Migu on 16/9/8.
//  Copyright © 2016年 Migu. All rights reserved.
//

#import "NSString+Extension.h"
#import <CommonCrypto/CommonDigest.h>
#import "NSData+Extension.h"
#import <CommonCrypto/CommonCryptor.h>

static NSString *kAESKey = @"*&~@!#()^%$+w_x2";
static NSString *kAESIv = @"(%*^~!)$#&@a_x+r";

@implementation NSString(Extension)

- (NSString *)MD5LowercaseString {
    return [self MD5UppercaseString].lowercaseString;
}

- (NSString *)MD5UppercaseString {
    const char *cStr = [self UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    return [NSString stringWithFormat:
            @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

- (NSString *)base64EncodeString {
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    return [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}

- (NSString *)base64DecodeString {
    NSData *data = [[NSData alloc] initWithBase64EncodedString:self options:NSDataBase64DecodingIgnoreUnknownCharacters];
    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

- (NSString *)AESEncryptString {
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSData *encryptData = [data AESEncryptWithKey:kAESKey iv:kAESIv];
    
    return [encryptData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}

- (NSString *)AESEncryptStringWithKey:(NSString *)key iv:(NSString *)iv {
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSData *encryptData = [data AESEncryptWithKey:key iv:iv];
    
    return [encryptData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}

- (NSString *)AESDecryptString {
    NSData *encryptData = [[NSData alloc] initWithBase64EncodedString:self options:NSDataBase64DecodingIgnoreUnknownCharacters];
    NSData *decryptData = [encryptData AESDecryptWithKey:kAESKey iv:kAESIv];
    
    return [[NSString alloc] initWithData:decryptData encoding:NSUTF8StringEncoding];
}

- (NSString *)AESDecryptStringWithKey:(NSString *)key iv:(NSString *)iv {
    NSData *encryptData = [[NSData alloc] initWithBase64EncodedString:self options:NSDataBase64DecodingIgnoreUnknownCharacters];
    NSData *decryptData = [encryptData AESDecryptWithKey:key iv:iv];
    
    return [[NSString alloc] initWithData:decryptData encoding:NSUTF8StringEncoding];
}
//- (NSString *)DESEncryptStringWithKey:(NSString *)key{
//    NSString *ciphertext = nil;
//    const char *textBytes = [self UTF8String];
//    size_t dataLength = [self length];
//    //==================
//    
//    uint8_t *bufferPtr = NULL;
//    size_t bufferPtrSize = 0;
//    size_t movedBytes = 0;
//    
//    bufferPtrSize = (dataLength + kCCBlockSizeDES) & ~(kCCBlockSizeDES - 1);
//    bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
//    memset((void *)bufferPtr, 0x0, bufferPtrSize);
//    
//    
//    NSString *testString = key;
//    NSData *testData = [testString dataUsingEncoding: NSUTF8StringEncoding];
//    Byte *iv = (Byte *)[testData bytes];
//    
//    
//    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,
//                                          kCCOptionPKCS7Padding,
//                                          [key UTF8String], kCCKeySizeDES,
//                                          iv,
//                                          textBytes, dataLength,
//                                          (void *)bufferPtr, bufferPtrSize,
//                                          &movedBytes);
//    if (cryptStatus == kCCSuccess) {
//        
//        ciphertext= [self parseByte2HexString:bufferPtr :(int)movedBytes];
//        
//    }
//    ciphertext=[ciphertext lowercaseString];//字符变小写
//    
//    return ciphertext ;
//    
//}


- (NSString *)URLEncodeString {
    NSString *encoded = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]", NULL, kCFStringEncodingUTF8));
    return encoded;
}

- (NSString *)URLEncodedStringAll{

    NSString *unencodedString = self;
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)unencodedString,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    return encodedString;
}

-(NSString *)URLDecodedStringAll{
  
    NSString *encodedString = self;
    NSString *decodedString  = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
                                                                                                                     (__bridge CFStringRef)encodedString,
                                                                                                                     CFSTR(""),
                                                                                                                     CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    return decodedString;
}

- (NSUInteger)textLength {
    return [self lengthOfBytesUsingEncoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)];
}

-(NSString *)splitNameOrId{
    NSMutableString *tempStr = [NSMutableString stringWithString:self];
    NSArray * arr = [self componentsSeparatedByString:@"@{"];
    
    for (NSString *str in arr) {
        
        if (![str containsString:@"@{"]&&![str containsString:@"}"]) {
            continue;
        }
        
        NSArray *subArr = [str componentsSeparatedByString:@"}"];
        NSString *sub = subArr.firstObject;
        NSString *subDic = [NSString stringWithFormat:@"{%@}",sub];
        
       // NSString * str=@"{\"message_type\":\"redpackage\",\"room_id\":\"120100328\"}";
        NSData *jsonData = [subDic dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dic =  [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
        NSRange range = [tempStr rangeOfString:subDic];
        if (dic == nil)
        {
            return tempStr.copy;
        }
        [tempStr replaceCharactersInRange:range withString:dic[@"userNickName"]];
        
    }
    
    return tempStr.copy;
}

- (NSArray *)splitDic{
    NSMutableArray *tempArr = [NSMutableArray array];
    NSArray * arr = [self componentsSeparatedByString:@"@{"];
    
    for (NSString *str in arr) {
        
        if (![str containsString:@"@{"]&&![str containsString:@"}"]) {
            continue;
        }
        
        NSArray *subArr = [str componentsSeparatedByString:@"}"];
        NSString *sub = subArr.firstObject;
        NSString *subDic = [NSString stringWithFormat:@"{%@}",sub];
        
        // NSString * str=@"{\"message_type\":\"redpackage\",\"room_id\":\"120100328\"}";
        NSData *jsonData = [subDic dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dic =  [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
        if (dic == nil) {
            return tempArr.copy;
        }
        [tempArr addObject:dic];
    }
    return tempArr.copy;
}


- (NSArray *)subStringFrom:(NSString *)startString to:(NSString *)endString{
    //  123//@{userNickName:aaa, uid:15}:nhgfd//@{userNickName:sdfggfhdgf, uid:15}:ju5y4w3q
    NSArray * arr = [self componentsSeparatedByString:startString];
    
    NSMutableArray *tempArr = [NSMutableArray array];
    for (NSString *str in arr) {
        if (![str containsString:endString]) {
            continue ;
        }
        NSRange startRange = NSMakeRange(0, 0);
        NSRange endRange = [str rangeOfString:endString];
        NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
        [tempArr addObject:[str substringWithRange:range]];
    }
    
    return tempArr;
    
}


@end
